using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MsgBackend.Api.Models;
using MsgBackend.Api.ParamModel;
using MsgBackend.Api.Repository;
using MsgBackend.Api.Utils;
using Microsoft.AspNetCore.Authorization;

namespace MsgBackend.Api.Controllers
{
    // [Authorize] 
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {
        private IRepository<Users> _usersRepository;

        private TokenParamter _tokenparamter;

        private readonly IConfiguration _configuration;

        public UserController(IRepository<Users> usersRepository, IConfiguration configuration)
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _tokenparamter = _configuration.GetSection("TokenParameter").Get<TokenParamter>();
        }

        //登录
        [AllowAnonymous]
        [HttpPost, Route("Login")]
        public ActionResult GetToken(ParamUser model)
        {

            var users = _usersRepository.Table;

            if (model.Username.Trim() == "" || model.Password.Trim() == "")
            {
                var res = new
                {
                    Code = 1002,
                    Data = "",
                    Msg = "账号密码不能为空，请重试"
                };
                return Ok(res);
            }
            else
            {
                var user = users.Where(x => x.Username == model.Username.Trim() && x.Password == model.Password.Trim()&&x.IsActived==true).FirstOrDefault();

                if (user == null)
                {
                    return Ok(
                    new
                    {
                        Code = 1002,
                        Data = "",
                        Msg = "账号密码错误或改用户被封禁，请确认后重试"
                    });

                };
                var token = TokenHelper.GenerateToekn(_tokenparamter, user);
                var refreshToken = "123456";
                var id = user.Id;
                //如果登录成功，需要获得token
                var res = new
                {
                    Code = 1000,
                    // Data=user,
                    Data = new { Token = token, RefreshToken = refreshToken, Id = id },
                    Msg = "登录成功"
                };
                return Ok(res);

            }
        }
        //获取所有用户
        [HttpGet]
        public ActionResult Get([FromQuery] Pager pager)
        {
            Console.WriteLine(pager.currentPage);

            //获取当前页
            var currentPage = pager.currentPage;

            //获取页面数据行数
            var pageSize = pager.pageSize;
            var users = _usersRepository.Table;
            var use =
                users
                    .Where(x => x.IsDeleted == false)
                    .Skip((currentPage - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();

            return Ok(new
            {
                Code = 1000,
                Data = use,
                Count =
                    users
                        .Where(x => x.IsDeleted == false)
                        .Count(),
                Msg = "获取成功"
            });
        }

        //查找用户数据
        [HttpGet, Route("Select")]
        public dynamic SelectUser([FromQuery] SelectMsg data)
        {
            var msg = data.msg;

            //获取当前页
            var currentPage = data.currentPage;

            //获取页面数据行数
            var pageSize = data.pageSize;

            var use = _usersRepository.Table;

            var u =
                use.Where(x => x.Username.Contains(msg))
                    .Where(x => x.IsDeleted == false)
                    .Take(pageSize)
                    .ToList();

            return Ok(new {
                Code = 1000,
                Data = u,
                Count =
                    use.Where(x => x.Username.Contains(msg))
                        .Where(x => x.IsDeleted == false)
                        .Count()
            });
        }

        //添加新的用户
        [HttpPost]
        public ActionResult Post(ParamUser model)
        {
            var users = _usersRepository.Table;
            var usename = users.Where(x =>x.Username==model.Username).FirstOrDefault();
            if(usename==null){
                var user =
                new Users {
                    Username = model.Username,
                    Password = model.Password,
                    IsActived = true,
                    IsDeleted = false
                };
            _usersRepository.Insert (user);
            return Ok(new { Code = 1000, Data = user, Msg = "添加成功" });
            }else{
                return Ok(new { Code = 1002, Data = "", Msg = "用户名已存在" });
            }
            
        }

        //修改用户状态
        [HttpPut, Route("statu")]
        public ActionResult PutStatu(Status model)
        {
            
            var user = _usersRepository.GetById(model.id);
            if (user != null)
            {
                if (model.isActived == false)
                {
                    user.IsActived = false;
                    _usersRepository.Update (user);
                    return Ok(new {
                        Code = 1000,
                        Data = user,
                        Msg = "修改成功"
                    });
                }
                else
                {
                    user.IsActived = true;
                    _usersRepository.Update (user);
                    return Ok(new {
                        Code = 1000,
                        Data = user,
                        Msg = "修改成功"
                    });
                }
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }

        //根据id修改指定用户
        [HttpPut("{id}")]
        public ActionResult Put(ParamUser model, int id)
        {
            var user = _usersRepository.GetById(id);

            if (user != null)
            {
                user.Username = model.Username;
                user.Password = model.Password;
                user.Remark = model.Remark;
                _usersRepository.Update (user);
                return Ok(new { Code = 1000, Data = user, Msg = "修改成功" });
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }
        
        // 根据用户名密码修改用户
        [HttpPut, Route("UserUpdate")]
        public ActionResult UserUpdate(ParamUpdateUser model)
        {
            var oldPassword = model.OldPassword;
            var Username = model.Username;
            var users = _usersRepository.Table;
            var user = users.Where(x => x.Username == Username && x.Password == oldPassword).FirstOrDefault();
            if (user != null)
            {
                user.Password = model.NewPassword;
                _usersRepository.Update(user);
                return Ok(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = "修改成功"
                });
            }
            return Ok(new
            {
                Code = 1002,
                Data = "",
                Msg = "修改失败"
            });

        }
        [HttpGet("getUserOne/{id}")]

        public ActionResult GetUserOne(int id)
        {
            var user = _usersRepository.GetById(id);
            return Ok(new
            {
                Code = 1000,
                Data = user,
                Msg = "获得成功"
            });
        }


        //删除用户数据
        [HttpDelete("{id}")]
        public ActionResult DeleteUser(int id)
        {
            var use = _usersRepository.GetById(id);
            if (use != null)
            {
                use.IsActived = false;
                use.IsDeleted = true;
                use.UpdatedTime = DateTime.Now;

                _usersRepository.Delete (use);

                return Ok(new {
                    Code = 1000,
                    Data = use,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                });
            }
            else
            {
                return Ok(new {
                    Code = 1002,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }
        }
    }
}
